package com.fjec.devops.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjec.common.annotation.OpeLog;
import com.fjec.common.protocol.JsonResult;
import com.fjec.devops.entity.InfoMarket;
import com.fjec.devops.service.MarketService;
import com.google.common.base.Strings;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/")
public class MarketController {
    @Autowired
    private MarketService marketService;

    /**
     * 获取市场列表
     *
     * @param page
     * @return
     */
    @GetMapping("/y/market/list")
    public JsonResult listMarkets(Page page) {
        Map<String, Object> result = marketService.listMarkets(page);
        return JsonResult.success().data(result).build();
    }

    /**
     * 查看市场详情
     *
     * @param markCode
     * @return
     */
    @GetMapping("/y/market/getByCode")
    public JsonResult getByCode(int markCode) {
        Map<String, Object> result = marketService.getByCode(markCode);
        return JsonResult.success().data(result).build();
    }

    /**
     * 创建或更新市场
     *
     * @param infoMarket
     * @param markPic
     * @param markMapPic
     * @return
     */
    @OpeLog(desc = "创建或更新市场")
    @PostMapping("/y/market/saveOrUpdate")
    public JsonResult saveOrUpdate(InfoMarket infoMarket, String markPic, Long markPicId, String markMapPic, Long markMapPicId) {
        marketService.saveOrUpdate(infoMarket, markPic, markPicId, markMapPic, markMapPicId);
        return JsonResult.SUCCESS;
    }

    /**
     * 获取用户列表
     *
     * @param searchBy
     * @param title
     * @param busiType
     * @param markCode
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/y/market/getBusinessesOfAllTypesByConditions")
    public JsonResult getBusinessesOfAllTypesByConditions(@RequestParam(required = false) Integer searchBy,
                                                          @RequestParam(required = false) String title,
                                                          @RequestParam(required = false) Integer busiType,
                                                          @RequestParam(required = false) Integer markCode,
                                                          @RequestParam(required = false) String startTime,
                                                          @RequestParam(required = false) String endTime,
                                                          Page page) {
        Map<String, Object> result = marketService.getBusinessesOfAllTypesByConditions(searchBy, title, busiType, markCode, startTime, endTime, page);

        List<Map<String, Object>> data = (List<Map<String, Object>>) result.get("data");

        data.forEach(m -> {
            Integer bt = MapUtils.getInteger(m, "busiType");
            String userType = "";
            switch (bt) {
                case 1:
                    userType = "普通用户";
                    break;
                case 2:
                    userType = "种植/养殖户";
                    break;
                case 3:
                    userType = "分拣厂合作社";
                    break;
                case 4:
                    userType = "物流/农资";
                    break;
                case 5:
                    userType = "包装物厂";
                    break;
                case 6:
                    userType = "超市采购商";
                    break;
                default:

            }
            m.put("userType", userType);
        });

        return JsonResult.success().data(data).total(MapUtils.getLong(result, "total")).build();
    }

    /**
     * 查看店铺详情
     *
     * @param busiId
     * @param busiType
     * @return
     */
    @GetMapping("/y/market/getBusinessInfo")
    public JsonResult getBusinessInfo(Long busiId, Integer busiType) {
        Map<String, Object> result = marketService.getBusinessInfo(busiId, busiType);

        return JsonResult.success().data(result).build();
    }

    /**
     * 获取订单列表
     *
     * @param searchBy
     * @param title
     * @param busiType
     * @param markCode
     * @param orderType
     * @param orderStatus
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/y/market/phy/order/getOrdersByConditions")
    public JsonResult getOrdersByConditions(@RequestParam(required = false) Integer searchBy,
                                            @RequestParam(required = false) String title,
                                            @RequestParam(required = false) Integer busiType,
                                            @RequestParam(required = false) Integer markCode,
                                            @RequestParam(required = false) Integer orderType,
                                            @RequestParam(required = false) Integer orderStatus,
                                            @RequestParam(required = false) String startTime,
                                            @RequestParam(required = false) String endTime,
                                            Page page) {
        Map<String, Object> result = marketService.getOrdersByConditions(searchBy, title, busiType, markCode,
                orderType, orderStatus, startTime, endTime, page);
        List<Map<String, Object>> data = (List<Map<String, Object>>) result.get("data");

        return JsonResult.success()
                .data(data)
                .total(MapUtils.getLong(result, "total"))
                .build();
    }

    /**
     * 获取店铺订单列表
     *
     * @param busiId
     * @return
     */
    @GetMapping("/y/market/phy/order/getOrdersByBusiId")
    public JsonResult getSubOrdersByBusiId(Long busiId, Integer busiType, Page page) {
        Map<String, Object> result = marketService.getOrdersByConditions(3, busiId.toString(), busiType, null,
                null, null, null, null, page);
        List<Map<String, Object>> dataList = (List<Map<String, Object>>) result.get("data");

        return JsonResult.success()
                .data(dataList)
                .total(MapUtils.getLong(result, "total"))
                .build();
    }

    /**
     * 查看订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/y/market/phy/order/getOrderDetailById")
    public JsonResult getOrderDetailById(Long id) {
        Map<String, Object> result = marketService.getOrderDetailById(id);
        String spuPics = MapUtils.getString(result, "spuPics");
        JSONArray a = new JSONArray(spuPics);
        result.put("spuPics", a);

        String complaintPics = MapUtils.getString(result, "complaintPics");
        if (!Strings.isNullOrEmpty(complaintPics)) {
            JSONArray c = new JSONArray(complaintPics);
            result.put("complaintPics", c);
        }

        String receiveInfo = MapUtils.getString(result, "receiveInfo");
        JSONObject b = new JSONObject(receiveInfo);
        result.put("receiveInfo", b);
        return JsonResult.success().data(result).build();
    }

    /**
     * 获取保证金列表
     *
     * @param searchBy
     * @param title
     * @param busiType
     * @param markCode
     * @param depoStatus
     * @param timedBy
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/y/market/getDepoInfoByConditions")
    public JsonResult getDepoInfoByConditions(@RequestParam(required = false) Integer searchBy,
                                              @RequestParam(required = false) String title,
                                              @RequestParam(required = false) Integer busiType,
                                              @RequestParam(required = false) Integer markCode,
                                              @RequestParam(required = false) Integer depoStatus,
                                              @RequestParam(required = false) Integer timedBy,
                                              @RequestParam(required = false) String startTime,
                                              @RequestParam(required = false) String endTime, Page page) {

        Map<String, Object> result = marketService.getDepoInfoByConditions(searchBy, title, busiType, markCode, depoStatus, timedBy, startTime, endTime, page);
        List<Map<String, Object>> data = (List) MapUtils.getObject(result, "data");
        data.forEach(m -> {
            Integer bt = MapUtils.getInteger(m, "busiType");
            switch (bt) {
                case 1:
                    m.put("busiTypeString", "普通用户");
                    break;
                case 2:
                    m.put("busiTypeString", "种植/养殖户");
                    break;
                case 3:
                    m.put("busiTypeString", "分拣厂合作社");
                    break;
                case 4:
                    m.put("busiTypeString", "物流/农资");
                    break;
                case 5:
                    m.put("busiTypeString", "包装物厂");
                    break;
                case 6:
                    m.put("busiTypeString", "超市采购商");
                    break;
                default:
            }

            Integer dt = MapUtils.getInteger(m, "depoStatus");
            switch (dt) {
                case 0:
                    m.put("depoStatusString", "未缴纳");
                    break;
                case 1:
                    m.put("depoStatusString", "已缴纳");
                    break;
                case 2:
                    m.put("depoStatusString", "申请退回");
                    break;
                case 3:
                    m.put("depoStatusString", "已退回");
                    break;
                default:
            }
        });
        Long totalDepo = MapUtils.getLong(result, "totalDepo");
        Map<String, Object> finalResult = new HashMap<>();
        finalResult.put("data", data);
        finalResult.put("totalDepo", totalDepo);
        return JsonResult.success().data(finalResult).total(MapUtils.getLong(result, "total")).build();
    }

    /**
     * 交易流水列表
     *
     * @param searchBy
     * @param title
     * @param orderType
     * @param sellerType
     * @param buyerType
     * @param page
     * @return
     */
    @GetMapping("/y/market/getTradingsByConditions")
    public JsonResult getTradingsByConditions(@RequestParam(required = false) Integer searchBy,
                                              @RequestParam(required = false) String title,
                                              @RequestParam(required = false) Integer orderType,
                                              @RequestParam(required = false) Integer sellerType,
                                              @RequestParam(required = false) Integer buyerType, Page page) {
        Map<String, Object> result = marketService.getTradingsByConditions(searchBy, title, orderType, sellerType, buyerType, page);
        return JsonResult.success()
                .data(result.get("data"))
                .total(MapUtils.getLong(result, "total"))
                .build();
    }

    /**
     * @param searchBy
     * @param title
     * @param busiType
     * @param markCode
     * @param orderType
     * @param orderStatus
     * @param startTime
     * @param endTime
     * @param page
     * @return
     */
    @GetMapping("/y/market/getOrderComplaintsByConditions")
    public JsonResult getOrderComplaintsByConditions(@RequestParam(required = false) Integer searchBy,
                                                     @RequestParam(required = false) String title,
                                                     @RequestParam(required = false) Integer busiType,
                                                     @RequestParam(required = false) Integer markCode,
                                                     @RequestParam(required = false) Integer orderType,
                                                     @RequestParam(required = false) Integer orderStatus,
                                                     @RequestParam(required = false) String startTime,
                                                     @RequestParam(required = false) String endTime,
                                                     Page page) {
        Map<String, Object> result = marketService.getOrderComplaintsByConditions(searchBy, title, busiType, markCode,
                orderType, orderStatus, startTime, endTime, page);
        List<Map<String, Object>> data = (List<Map<String, Object>>) result.get("data");
        data.forEach(m -> {
            Integer bt = MapUtils.getInteger(m, "shopType");
            String userType = "";
            switch (bt) {
                case 1:
                    userType = "普通用户";
                    break;
                case 2:
                    userType = "种植/养殖户";
                    break;
                case 3:
                    userType = "分拣厂合作社";
                    break;
                case 4:
                    userType = "物流/农资";
                    break;
                case 5:
                    userType = "包装物厂";
                    break;
                case 6:
                    userType = "超市采购商";
                    break;
                default:

            }
            m.put("shopType", userType);

            Integer ot = MapUtils.getInteger(m, "orderType");
            String oType = "";
            switch (ot) {
                case 1:
                    oType = "零售";
                    break;
                case 2:
                    oType = "批采";
                    break;
                default:
            }
            m.put("orderType", oType);

            Integer hr = MapUtils.getInteger(m, "handleResult");
            String handleResult = "";
            switch (hr) {
                case 0:
                    handleResult = "未处理";
                    break;
                case 1:
                    handleResult = "已处理";
                    break;
                case 2:
                    handleResult = "已处理";
                    break;
                default:
            }
            m.put("result", handleResult);
        });
        return JsonResult.success()
                .data(result.get("data"))
                .total(MapUtils.getLong(result, "total"))
                .build();
    }

    /**
     * 投诉处理
     *
     * @param complaintId
     * @param orderId
     * @param subOrderId
     * @param handleType
     * @param amount
     * @return
     */
    @OpeLog(desc = "投诉处理")
    @PostMapping("/y/complaint/handle")
    public JsonResult handleComplaint(Long complaintId, Long orderId, Long subOrderId, Integer handleType, String amount, String complaintText) {
        if (handleType == 2 && amount != null && Double.parseDouble(amount) <= 0)
            return JsonResult.FAILURE;
        int result = marketService.handleComplaint(orderId, subOrderId, complaintId, handleType, amount, complaintText);
        if (result == 0)
            return JsonResult.SUCCESS;
        else
            return JsonResult.FAILURE;
    }

    /**
     * 查看银行账户信息
     * @param busiId
     * @return
     */
    @GetMapping("/y/get/account/info")
    public JsonResult getAccountInfo(Long busiId) {
        Map<String, Object> result = marketService.getAccountInfo(busiId);
        return JsonResult.success().data(result).build();
    }

    /**
     * 确认保证金已退回
     * @param busiId
     * @param busiType
     * @return
     */
    @PostMapping("/y/refund/deposit")
    public JsonResult refundDeposit(Long busiId, Integer busiType) {
        int code = marketService.refundDeposit(busiId, busiType);
        if (code != 1)
            return JsonResult.FAILURE;
        return JsonResult.SUCCESS;
    }

}
